package lj.netty.tool;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import io.netty.buffer.Unpooled;
import io.netty.handler.codec.ByteToMessageDecoder;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.FixedLengthFrameDecoder;
import io.netty.handler.codec.LineBasedFrameDecoder;

/**
 * netty 拆包构造器
 * @author: liuwenju
 * @date: 2023/6/6 9:40
 * @version: 1.0
 */
public class LJTNettyStructPackage {

    /** 分隔符 */
    private String separate;

    /** 固定长度 */
    private Integer fixLength;

    /** 包最大长度 - 100M */
    private int maxPackLength = 1024 * 1024 * 1024;

    public LJTNettyStructPackage(String separate) {
        this.separate = separate;
    }

    public LJTNettyStructPackage() {
    }

    public ByteToMessageDecoder struct() {
        if (StrUtil.isNotBlank(separate)) {
            return new DelimiterBasedFrameDecoder(maxPackLength, Unpooled.copiedBuffer(separate.getBytes()));
        }
        if (ObjectUtil.isNotNull(fixLength)) {
            return new FixedLengthFrameDecoder(fixLength);
        }
        return new LineBasedFrameDecoder(maxPackLength);
    }
}
